<template>
  <div class="cart">
    <TypeNav />
    <div class="empty" v-show="!cartList.length">
      <img src="./images/empty.gif" />
    </div>
    <div v-show="cartList.length">
      <h4>全部商品</h4>
      <div class="cart-main">
        <div class="cart-th">
          <div class="cart-th1">全部</div>
          <div class="cart-th2">商品</div>
          <div class="cart-th3">单价（元）</div>
          <div class="cart-th4">数量</div>
          <div class="cart-th5">小计（元）</div>
          <div class="cart-th6">操作</div>
        </div>
        <div class="cart-body" v-for="(cart, index) in cartList" :key="index">
          <ul
            class="cart-list"
            v-for="cartInfo in cart.cartInfoList"
            :key="cartInfo.id"
          >
            <li class="cart-list-con1">
              <!-- 单选框 -->
              <input
                type="checkbox"
                name="chk_list"
                :checked="cartInfo.isChecked"
                @click="handleCheck(cartInfo)"
              />
            </li>
            <li class="cart-list-con2">
              <img :src="cartInfo.imgUrl" />
              <div class="item-msg">{{ cartInfo.skuName }}</div>
            </li>
            <li class="cart-list-con4">
              <span class="price">{{ cartInfo.skuPrice }}</span>
            </li>
            <li class="cart-list-con5">
              <a @click="changeSkuNum('decrement', cartInfo)" class="mins">-</a>
              <input
                @change="changeSkuNum('change', cartInfo, $event)"
                type="text"
                :value="cartInfo.skuNum"
                class="itxt"
              />
              <a @click="changeSkuNum('increment', cartInfo)" class="plus">+</a>
            </li>
            <li class="cart-list-con6">
              <span class="sum">{{ cartInfo.skuNum * cartInfo.skuPrice }}</span>
            </li>
            <li class="cart-list-con7">
              <a class="sindelet" @click="handleDelete(cartInfo.skuId)">删除</a>
              <br />
            </li>
          </ul>
        </div>
      </div>
      <div class="cart-tool">
        <div class="select-all">
          <!-- 全选框 -->
          <input
            class="chooseAll"
            type="checkbox"
            :checked="isAll"
            @click="handleCheckAll"
          />
          <span>全选</span>
        </div>
        <div class="option">
          <a @click="handleDeleteChecked">删除选中的商品</a>
        </div>
        <div class="money-box">
          <div class="chosed">
            已选择 <span>{{ total }}</span
            >件商品
          </div>
          <div class="sumprice">
            <em>总价（不含运费） ：</em>
            <i class="summoney">{{ totalPrice }} 元</i>
          </div>
          <div class="sumbtn">
            <a class="sum-btn" href="###" target="_blank">结算</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  reqCartList,
  reqCheckSkuInCart,
  reqCheckAllSkuInCart,
  reqDeleteSkuInCart,
  reqBatchDeleteSkuInCart,
  reqAddOrUpdateCart,
} from "@/api";
import { skuNumReg } from "@/utils/reg";
import throttle from "lodash/throttle";

export default {
  name: "Cart",
  data() {
    return {
      cartList: [], //购物车数据
    };
  },
  computed: {
    //计算所有的商品是否勾选
    isAll() {
      return this.cartList.every((cart) => {
        return cart.cartInfoList.every((cartInfo) => {
          return cartInfo.isChecked === 1;
        });
      });
    },
    //总数
    total() {
      let n = 0;
      this.cartList.forEach((cart) => {
        cart.cartInfoList.forEach((cartInfo) => {
          if (cartInfo.isChecked) {
            n += cartInfo.skuNum;
          }
        });
      });
      return n;

      // reduce方法//
      // return this.cartList.reduce((pre1,cart)=>{
      //   return pre1 + cart.cartInfoList.reduce((pre2,cartInfo)=>{
      //     return pre2 += (cartInfo.isChecked ? cartInfo.skuNum : 0)
      //   },0)
      // },0)
    },
    totalPrice() {
      let n = 0;
      this.cartList.forEach((cart)=>{
        cart.cartInfoList.forEach((cartInfo)=>{
          if (cartInfo.isChecked) {
            n += (cartInfo.skuNum * cartInfo.skuPrice)
          }
        })
      })
      return n;

      //reduce方法//
      // return this.cartList.reduce((pre1, cart) => {
      //   return pre1 + cart.cartInfoList.reduce((pre2, cartInfo) => {
      //     return (pre2 += (cartInfo.isChecked ? cartInfo.skuNum*cartInfo.skuPrice : 0));
      //   }, 0);
      // }, 0);
    },
  },
  methods: {
    //根据某个操作返回的result刷新购物车数据
    refreshCart(result) {
      //若操作不成功，提示一下因为啥
      if (result.code !== 200) alert(result.message);
      //刷数据
      this.getCartList();
    },
    //获取购物车数据
    async getCartList() {
      let result = await reqCartList();
      if (result.code === 200) this.cartList = result.data;
      else alert(result.message);
    },
    //单选框的点击事件
    async handleCheck(cartInfo) {
      //获取当前商品的id 和 是否勾选状态
      let { skuId, isChecked } = cartInfo;
      //维护一个新的勾选值
      isChecked = isChecked ? 0 : 1;
      //让页面更加丝滑
      cartInfo.isChecked = isChecked;
      //发送请求
      let result = await reqCheckSkuInCart(skuId, isChecked);
      //刷新
      this.refreshCart(result);
    },
    //全选框的点击事件
    async handleCheckAll() {
      //维护好一个isChecked
      let isChecked = this.isAll ? 0 : 1;
      //收集购物车中所有商品的id,放在数组里面
      let skuIdList = [];
      //遍历购物车收集id
      this.cartList.forEach((cart) => {
        cart.cartInfoList.forEach((cartInfo) => {
          //让页面丝滑
          cartInfo.isChecked = isChecked;
          //把id放进数组里面
          skuIdList.push(cartInfo.skuId);
        });
      });
      //发送请求
      let result = await reqCheckAllSkuInCart(skuIdList, isChecked);
      //成功刷数据
      this.refreshCart(result);
    },
    //删除单个商品
    async handleDelete(id) {
      if (confirm("确认删除吗?")) {
        //发送请求删除
        let result = await reqDeleteSkuInCart(id);
        //成功刷数据
        this.refreshCart(result);
      }
    },
    //删除选中的所有商品
    async handleDeleteChecked() {
      if (confirm("确定删除所选的商品吗?")) {
        //准备数组收集所有的id
        let skuIdList = [];
        this.cartList.forEach((cart) => {
          cart.cartInfoList.forEach((cartInfo) => {
            if (cartInfo.isChecked) skuIdList.push(cartInfo.skuId);
          });
        });
        //请求删除多个
        let result = await reqBatchDeleteSkuInCart(skuIdList);
        //成功刷新刷新数据
        this.refreshCart(result);
      }
    },
    //购物车修改数量
    changeSkuNum: throttle(
      async function (type, { skuId, skuNum }, event) {
        //通知服务器更新数据 联系服务器修改数量
        const tellServerUpdateSkuNum = async (skuId, disNum) => {
          //发送请求
          let result = await reqAddOrUpdateCart(skuId, disNum);
          //刷新数据
          this.refreshCart(result);
        };

        switch (type) {
          //增加
          case "increment":
            if (skuNum === 200) alert("最大购买数量为200");
            else tellServerUpdateSkuNum(skuId, 1);

            break;
          //减少
          case "decrement":
            if (skuNum === 1) alert("最小购买数量为1");
            else tellServerUpdateSkuNum(skuId, -1);
            break;
          //手动输入数字
          case "change":
            //获取用户输入
            let { value } = event.target;
            //校验用户输入
            if (skuNumReg.test(value)) {
              //用户名合法算出插值
              let disNum = value - skuNum;
              //更新数据
              tellServerUpdateSkuNum(skuId, disNum);
            } else if (value > 200) {
              //计算差值
              let disNum = 200 - skuNum;
              //更新数据
              tellServerUpdateSkuNum(skuId, disNum);
            } else {
              event.target.value = skuNum;
            }
            break;
        }
      },
      500,
      { trailing: false }
    ),
  },
  mounted() {
    //组件一挂载就挂载购物车数据
    this.getCartList();
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
            cursor: pointer;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
            cursor: pointer;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
            font-size: 16px;
            cursor: pointer;
          }
          a:hover {
            color: #e1251b;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        text-decoration: none;
        padding: 0 10px;
        color: #666;
      }
      a:hover {
        cursor: pointer;
        color: #e1251b;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
</style>
